<?php

namespace Data;

class User extends Base {

    /**
     * 用户登陆标记的前缀.
     */
    const USER_LOGIN_MASK = 'user_login_mask';

    const USER_WEIXIN_OPEIN_ID = 'user_weixin_opein_id';

    const USER_FORGET_PASSWORD_TOKEN = 'user_forget_token_';

    const HISTORYSEARCH_KEY = 'HistorySearch_key'; //搜索记录key值

    const OPEN_USER_TYPE_WEIXIN = 1;

    /**
     * 根据手机号获取Uid
     *
     * @param $phoneNum
     * @return int
     */
    public function getUidByPhoneNum($phoneNum) {
        $condition = array(
            'PhoneNum' => $phoneNum
        );
        $result = $this->select('Uid')->where($condition)->findOne();
        $uid = 0;
        if ($result) {
            $uid = $result['Uid'];
        }
        return $uid;
    }

    public function getInfoByPhone($phone) {
        $condition = array(
            'PhoneNum' => $phone,
            'Status' => self::IS_YES,
        );
        $result = $this->where($condition)->findOne();
        return $result;
    }

    /**
     * 根据添加用户返回用户Uid
     *
     * @param $data
     * @return int
     */
    public function addUser($data) {
        $line = $this->insert($data);
        return $line;
    }

    /**
     * 设置用户的一个登陆标记.
     *
     * @param string  $mask 用户cookie中的唯一值.
     * @param integer $uid  用户id.
     *
     * @return void
     */
    public function setUserLoginMask($mask, $uid) {
        $redis = $this->getRedis();
        $key = self::USER_LOGIN_MASK . $mask;
        $redis->set($key, $uid);
        $redis->expire($key, 86400);
    }

    /**
     * 获取当前用户的信息.
     *
     * @param string $mask 用户cookie中的唯一值.
     *
     * @return array
     */
    public function getCurrentUserInfo($mask) {
        $uid = $this->getCurrentUid($mask);
        $userInfo = array();
        if (empty($uid)) {
            return $userInfo;
        }
        // 用uid获取数据库中的用户信息
        $userInfo = $this->getUserInfoByUid($uid);
        return $userInfo;
    }

    /**
     * 获取当前用户的Uid.
     *
     * @param string $mask 用户cookie中的唯一值.
     *
     * @return integer
     */
    private function getCurrentUid($mask) {
        $redis = $this->getRedis();
        $key = self::USER_LOGIN_MASK . $mask;
        $uid = $redis->get($key);
        return $uid;
    }

    /**
     * 通过用户id获取用户信息.
     *
     * @param integer $uid 用户id.
     *
     * @return array
     */
    public function getUserInfoByUid($uid) {
        $condition = array(
            'Uid' => $uid
        );
        $userInfo = $this->where($condition)->findOne();
        return $userInfo;
    }

    public function getUserInfoByPhone($phone) {
        $condition = array(
            'PhoneNum' => $phone,
        );
        $userInfo = $this->where($condition)->findOne();
        return $userInfo;
    }
}

